import camelCase from 'camelcase';
import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { View, StyleSheet, Text } from "react-native";
import { Popup, Utils, Notification } from 'tuya-panel-kit';
import TYSdk from '../../api';
import Button from '../../components/Button';
import GridLayout from '../../components/GridLayout';
import dpCodes from '../../config/dpCodes';
import Strings from '../../i18n';
import icons from '../../res/iconfont.json';
import Res from '../../res';
import { store } from '../../redux/configureStore';
import { debounce } from '../../utils';

const { isIphoneX, convertX: cx, convertY: cy, viewWidth } = Utils.RatioUtils;

const TYDevice = TYSdk.device;
const TYNative = TYSdk.native;

const {
  power: powerCode,
  mode: modeCode,
  anion: anionCode,
  childLock: childLockCode,
  light: lightCode,
  uv: uvCode,
  wet: wetCode,
  filterReset: filterResetCode,
  countdownSet: countdownSetCode,
  speed: speedCode,
  fault: faultCode,
} = dpCodes;

class HomeBottomView extends Component {
  static propTypes = {
    dpState: PropTypes.object,
    power: PropTypes.bool,
    dps: PropTypes.arrayOf(
      PropTypes.shape({
        code: PropTypes.string.isRequired,
      })
    ).isRequired,
  };

  static defaultProps = {
    dpState: {},
    power: false,
  };

  constructor(props) {
    super(props);
    this.state = {
      dps: props.dps,
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    this.setState({
      dps: nextProps.dps,
    });
  }

  getData() {
    const { power, speed, countdownSet } = this.props;
    const { dps } = this.state;
    // console.log('底部按钮：', dps);
    // 下面这俩是必须有的
    const head = {
      key: 'power',
      label: Strings.getLang('power'),
      icon: power ? Res.powerSel : Res.power,
      onPress: this._handleTogglePower,
    };
    const timing = {
      key: 'timing',
      label: Strings.getLang('countdown_set'),
      icon: countdownSet !== '0' && power ? Res.timingSel : Res.timing,
      onPress: this._handleTiming,
    };
    const fan = {
      key: 'fan',
      label: speed === 'sleep' ? Strings.getLang('sleep') : Strings.getLang('strong'),
      icon: speed === 'sleep' ? (power ? Res.fanSleep : Res.fanSleepDis) : (power ? Res.fanStrong : Res.fanStrongDis),
      onPress: this._handleSpeed,
    };
    const tail = {
      key: 'more',
      label: Strings.getLang('more'),
      // label: Strings.getLang(!power ? 'schedule' : 'setting'),
      icon: Res.more,
      // icon: !power ? icons.time : icons.setting,
      onPress: this._handleMore,
      selected: true,
    };
    const mode1 = {
      key: '1',
      label: '南美风',
      icon: Res.fmode1,
      onPress: this._handleMore,
    };
    const mode2 = {
      key: '2',
      label: '溪流风',
      icon: Res.fmode2,
      onPress: this._handleMore,
    };
    const mode3 = {
      key: '3',
      label: '白光',
      icon: Res.fmode3,
      onPress: this._handleMore,
    };
    const mode4 = {
      key: '4',
      label: '夜灯模式',
      icon: Res.fmode4,
      onPress: this._handleMore,
    };
    const mode5 = {
      key: '5',
      label: '日光',
      icon: Res.fmode5,
      onPress: this._handleMore,
    };
    const mode6 = {
      key: '6',
      label: '流光',
      icon: Res.fmode6,
      onPress: this._handleMore,
    };
    const mode7 = {
      key: '7',
      label: '水草灯',
      icon: Res.fmode7,
      onPress: this._handleMore,
    };
    const data = dps.map(dpInfo => {
      const disabled = !power;
      return {
        key: dpInfo.code,
        label: Strings.getDpLang(dpInfo.code),
        icon:
          dpInfo.code === 'fan_speed_enum' // 兼容老DP...
            ? Res.fanSleep
            : icons[camelCase(dpInfo.code)],
        disabled,
        onPress: () => this._handleDpItemPress(dpInfo),
      };
    });

    // data.unshift(fan);
    data.unshift(timing);
    // data.unshift(head);
    data.push(mode1);
    // data.push(mode2);
    // data.push(mode3);
    // data.push(mode4);
    // data.push(mode5);
    // data.push(mode6);
    // data.push(mode7);

    return data;
  }

  _handleTogglePower = debounce(() => {
    const { power, fault } = this.props;
    // 除了E3,E4，其它故障不能开机
    if (fault !== 0) {
      const errorBinary = fault.toString(2);
      const newStr = errorBinary.split('').reverse().join('');

      let errorString = '';
      let flage = false;

      for (let i = 0; i < newStr.length; i++) {
        const err = newStr[i];
        if (err === '1') {
          if (i < 3 || i > 4) {
            flage = true;
          }
          if (errorString === '') {
            errorString = errorList[i];
          } else {
            errorString = `${errorString}\n${errorList[i]}`;
          }
        }
      }

      if (flage === true) {
        Notification.show({
          message: errorString,
          variant: 'warning',
          style: { marginTop: 10 },
        });
        return;
      }
    }

    TYDevice.putDeviceData({
      [powerCode]: !power,
    });
  });

  _handleTiming = () => {
    // const { power } = this.props;
    // if (!power) return;

    const dps = [
      // 设置界面的数据
      // devInfo.schema[anionCode],
      // devInfo.schema[childLockCode],
      // devInfo.schema[lightCode],
      // devInfo.schema[uvCode],
      // devInfo.schema[wetCode],
      // devInfo.schema[wetCode],
      // devInfo.schema[filterResetCode],
      // devInfo.schema[countdownSetCode],
    ];
    // TYSdk.Navigator.push({
    //   id: 'timing',
    //   title: Strings.getLang('timing'),
    //   showDpFun: power,
    //   dps,
    // });
    const dpId = '116';
    const dpName = '喂食份数';
    TYNative.gotoDpAlarm({
      category: 'category__switch',
      repeat: 0,
      data: [
        {
          dpId,
          dpName,
          selected: 0, // DP 默认值的 index
          rangeKeys: ['1', '2', '3', '4', '5'],
          rangeValues: ['1', '2', '3', '4', '5'], // 只能为字符串类型的数组
        },
      ],
    });
  };

  _handleSpeed = debounce(() => {
    const { speed, power, mode } = this.props;
    if (!power || mode === 'dry') return;
    TYDevice.putDeviceData({
      [speedCode]: speed === 'sleep' ? 'strong' : 'sleep',
    });
  });

  _handleMore = () => {
    // const { power } = this.props;
    // const { devInfo = {} } = store.getState();
    // const dps = [
      // 设置界面的数据
      // devInfo.schema[anionCode],
      // devInfo.schema[childLockCode],
      // devInfo.schema[lightCode],
      // devInfo.schema[uvCode],
      // devInfo.schema[wetCode],
      // devInfo.schema[wetCode],
      // devInfo.schema[filterResetCode],
      // devInfo.schema[countdownSetCode],
    // ];

    // TYSdk.Navigator.push({
    //   id: 'setting',
    //   title: Strings.getLang('more'),
    //   showDpFun: power,
    //   dps,
    // });
  };

  _handleDpItemPress(dpInfo) {
    const { code, type, range } = dpInfo;
    const value = store.getState().dpState[code];
    if (type === 'bool') {
      TYDevice.putDeviceData({
        [code]: !value,
      });
    } else if (type === 'enum') {
      if (code === modeCode && range.length === 1) {
        TYDevice.putDeviceData({
          [code]: range[0],
        });
        return;
      }
      const rangeStrings = range.map(v => ({
        key: v,
        title: Strings.getDpLang(code, v),
        value: v,
      }));
      Popup.list({
        title: Strings.getDpLang(code),
        footerType: 'singleCancel',
        cancelText: Strings.getLang('cancel'),
        value,
        dataSource: rangeStrings,
        styles: { title: { width: viewWidth - 28 } },
        onSelect: v => {
          TYDevice.putDeviceData({
            [code]: v,
          });
          Popup.close();
        },
      });
    }
  }

  _handleSettingPress = () => {
    const { power } = this.props;
    const { devInfo = {} } = store.getState();
    const dps = [
      // 设置界面的数据
      // devInfo.schema[anionCode],
      // devInfo.schema[childLockCode],
      // devInfo.schema[lightCode],
      // devInfo.schema[uvCode],
      // devInfo.schema[wetCode],
      // devInfo.schema[wetCode],
      // devInfo.schema[filterResetCode],
      // devInfo.schema[countdownSetCode],
    ];
    if (!power) {
      const data = [
        {
          dpId: TYDevice.getDpIdByCode(powerCode),
          dpName: Strings.getLang('power'),
          selected: 0,
          rangeKeys: [true, false],
          rangeValues: [Strings.getLang('switchOn'), Strings.getLang('switchOff')],
        },
      ];
      TYNative.gotoDpAlarm({
        category: 'category__switch',
        repeat: 0,
        data,
      });
    } else {
      TYSdk.Navigator.push({
        id: 'setting',
        title: Strings.getLang('setting'),
        showDpFun: power,
        dps,
      });
    }
  };

  render() {
    const tabBgColor = 'rgba(230,238,247,1)';
    const activeFontColor = 'rgba(66,150,245,1)';
    const inActiveIconBgColor = 'rgba(255, 255, 255, 0.1)'; // 不可点击颜色
    const activeIconBgColor = 'rgba(255,255,255,1)';
    return (
      <View style={[styles.container, { backgroundColor: tabBgColor }]}>
        <GridLayout style={styles.gridLayout} rowNum={1} data={this.getData()}>
          {({ disabled, selected, ...props }) => {
            const iconColor = disabled ? activeIconBgColor : activeFontColor;
            const iconBgColor = disabled ? inActiveIconBgColor : activeIconBgColor;
            return (
              <Button
                {...props}
                accessibilityLabel={`HomeScene_BottomView_${camelCase(props.key, {
                  pascalCase: true,
                })}`}
                // style={styles.btn}
                disabled={disabled}
                selected={selected}
                // iconColor={iconColor}
                iconStyle={styles.icon}
                labelStyle={[styles.label, { color: iconColor }]}
              />
            );
          }}
        </GridLayout>
      </View>
    );
  }
}

const errorList = [
  '水泵保护中！',
  '满水故障，请倒水！',
  '高温故障，请将设备放置在较低环境温度下工作！',
  '防冻结保护中！',
  '防冻结保护中！',
  '环温传感器故障，请联系售后！',
  '管温传感器故障，请联系售后！',
  '冷媒泄露，请联系售后！',
  '温湿度模块故障，请联系售后！',
];

const styles = StyleSheet.create({
  container: {
    alignSelf: 'stretch',
  },

  gridLayout: {
    height: isIphoneX ? 200 : cy(150),
    paddingBottom: isIphoneX ? 20 : 0,
  },

  btn: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },

  label: {
    marginTop: cy(6),
    fontSize: Math.max(10, cx(10)),
    color: '#fff',
  },

  icon: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 48,
    height: 48,
    borderRadius: 24,
    color: '#22a8dc',
  },
});

export default connect(({ dpState }) => ({
  dpState,
  power: dpState[powerCode],
  anion: dpState[anionCode],
  childLock: dpState[childLockCode],
  light: dpState[lightCode],
  uv: dpState[uvCode],
  wet: dpState[wetCode],
  filterReset: dpState[filterResetCode],
  countdownSet: dpState[countdownSetCode],
  speed: dpState[speedCode],
  mode: dpState[modeCode],
  fault: dpState[faultCode],
}))(HomeBottomView);
